package springinpractice.common.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

/*
 * Author       :       Willie Wheeler and John Wheeler
 * Book         :       'Spring In Practice' [Book written by Willie Wheeler and John Wheeler]
 */

public abstract class AbstractHibernateDao<T extends Object> implements AbstractDao<T> {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	private Class<T> domainClass;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	@SuppressWarnings("unchecked")
	private Class<T> getDomainClass() {
	    if (domainClass == null) {
	    	ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass();
	        this.domainClass = (Class<T>) thisType.getActualTypeArguments()[0];
	    }
	    return domainClass;
	}
	
	private String getDomainClassName() {
		return getDomainClass().getName();
	}
	
	public void save(T t) {
		getSession().save(t);
	}
	
	@SuppressWarnings("unchecked")
	public T get(Long id) {
		return (T) getSession().get(getDomainClass(), id);
	}
	
	@SuppressWarnings("unchecked")
	public T load(Long id) {
		return (T) getSession().load(getDomainClass(), id);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getList() {
		Query q = getSession().createQuery("from " + getDomainClassName());
		return q.list();
	}
	
	public void update(T t) {
		getSession().update(t);
	}
	
	public void delete(T t) {
		getSession().delete(t);
	}
	
	public void deleteById(Long id) {
		getSession().delete(load(id));
	}
	
	public void deleteAll() {
		Query q = getSession().createQuery("delete " + getDomainClassName());
		q.executeUpdate();
	}
	
	public long count() {
		Query q = getSession()
			.createQuery("select count(*) from " + getDomainClassName());
		return (Long) q.uniqueResult();
	}
}
